package ink.teamwork.battery.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

@Slf4j
public class JSONUtils {

    private static final ObjectMapper OBJECT_MAPPER;

    static {
        OBJECT_MAPPER = new ObjectMapper();
        // 注册 JavaTimeModule 以支持 Java 8 的日期时间类型
        OBJECT_MAPPER.registerModule(new JavaTimeModule());
    }

    @SneakyThrows
    public static String toJSONString(Object object) {
        return OBJECT_MAPPER.writeValueAsString(object);
    }

    @SneakyThrows
    public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) {
        return OBJECT_MAPPER.readValue(OBJECT_MAPPER.writeValueAsString(map), clazz);
    }

    @SneakyThrows
    public static <T> T jsonToBean(String json, Class<T> clazz) {
        return OBJECT_MAPPER.readValue(json, clazz);
    }

    /**
     * 将 JSON 字符串转换为指定类型的对象列表
     *
     * @param json          JSON 字符串
     * @param typeReference TypeReference 对象，用于指定列表元素的类型
     * @param <T>           列表元素的类型
     * @return 转换后的对象列表
     */
    @SneakyThrows
    public static <T> List<T> jsonToList(String json, TypeReference<List<T>> typeReference) {
        return OBJECT_MAPPER.readValue(json, typeReference);
    }
}
